/**
 * 路由处理函数模块中，专门负责存放每个路由对应的处理函数
 */

/**
 * 在这里定义和用户相关的路由处理函数，供 /router/user.js 模块进行调用
 */
const db = require("../db/index");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("../config");

exports.regUser = (req, res) => {
  // 获取客户端提交用户的信息
  const user = req.body;
  console.log(user);
  if (!user.username || !user.password) {
    // 缺少必要参数
    return res.json({ status: 1, message: "缺少必要参数" });
  }
  const sql = "select * from tf_user where user_name=?";
  db.query(sql, user.username, function (err, results) {
    if (err) {
      res.json({ status: 1, message: err.message });
      return res;
    }
    if (results.length > 0) {
      // 用户名被占用
      return res.json({ status: 1, message: "用户名被占用" });
    }

    user.password = bcrypt.hashSync(user.password, 10);
    const sqlStr = "insert into tf_user set ?";
    console.log(sqlStr);
    db.query(
      sqlStr,
      { user_name: user.username, password: user.password },
      function (err, results) {
        if (err) {
          res.json({ status: 1, message: err.message });
          return res;
        }
        if (results.affectedRows !== 1) {
          res.json({ status: 1, message: "注册用户失败，请稍后再试！" });
          return res;
        }
        // 注册成功
        return res.json({ status: 0, message: "注册成功！" });
      }
    );
  });
};

exports.login = (req, res) => {
  const user = req.body;
  const querySql = `select * from tf_user where user_name = ?`;
  db.query(querySql, user.username, (err, results) => {
    if (err) {
      return res.json({ status: 1, message: err.message });
    }
    if (results.length !== 1) {
      return res.json({ status: 1, message: "登录失败！" });
    }
    // 比较密码是否正确
    const compareRes = bcrypt.compareSync(user.password, results[0].password);
    if (!compareRes) {
      return res.json({ status: 1, message: '登录失败"密码错误"！' });
    }
    // 登录成功,生产Token字符串
    // 生产Token字符串时,一定要剔除密码和头像的值
    const userInfo = { ...results[0], password: "", user_pic: "" };
    const tokenStr = jwt.sign(userInfo, config.jwtSecretKey, {
      expiresIn: config.expiresIn,
    });
    return res.json({
      status: 0,
      message: "登录成功！",
      token: "Bearer " + tokenStr,
    });
  });
};
